package com.example.demo.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * @program: demo
 * @author: JCM
 * @create: 2023-07-25 20:52
 * @description:
 **/
// 1. 添加 @ControllerAdvice 注解
@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {
    // 2. 添加方法处理异常
    @ExceptionHandler(NullPointerException.class)
    public HashMap<String,Object> nullException(NullPointerException e) {
        HashMap<String,Object> result = new HashMap<>();
        result.put("code","-1");
        result.put("msg","空指针异常:" + e.getMessage());
        result.put("data",null);
        return result;
    }

}
